"""
下载线程模块 - 处理后台下载任务
"""

import traceback
from PySide2.QtCore import QThread, Signal


class DownloadThread(QThread):
    """下载线程类，用于后台执行下载任务"""
    update_log = Signal(str)
    update_progress = Signal(float)
    finished = Signal()
    error = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.func = None
        self.args = None
        self._stop_requested = False

    def set_params(self, func, args):
        """设置要执行的函数和参数"""
        self.func = func
        self.args = args

    def request_stop(self):
        """请求停止下载"""
        self._stop_requested = True

    def run(self):
        """执行下载任务"""
        try:
            if self.func and self.args and not self._stop_requested:
                # 添加线程安全检查
                if hasattr(self, 'update_log'):
                    self.update_log.emit("下载线程开始执行...")

                self.func(*self.args)

                if not self._stop_requested:
                    if hasattr(self, 'update_log'):
                        self.update_log.emit("下载任务完成")
                    self.finished.emit()
        except Exception as e:
            if not self._stop_requested:
                error_msg = f"{str(e)}\n详细错误:\n{traceback.format_exc()}"
                # 记录错误到日志文件
                try:
                    import logging
                    logging.error(f"下载线程异常: {error_msg}")
                except:
                    pass
                self.error.emit(error_msg)
        finally:
            # 清理资源
            self.func = None
            self.args = None
            self._stop_requested = False

    def terminate(self):
        """终止线程（重写以添加清理）"""
        self._stop_requested = True
        super().terminate()

    def quit(self):
        """退出线程（重写以添加清理）"""
        self._stop_requested = True
        super().quit()
